package com.ojoin.trade.common.web.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ojoin.trade.common.web.dao.BaseDao;
import com.ojoin.trade.common.web.dao.OfficeDao;
import com.ojoin.trade.common.web.domain.Office;
import com.ojoin.trade.common.web.domain.User;
import com.ojoin.trade.common.web.service.OfficeService;
import com.ojoin.trade.common.web.service.SysManageService;

@Service
public class OfficeServiceImpl extends BaseServiceImpl<Office> implements OfficeService {

	@Autowired 
	private OfficeDao dao;
	
	@Autowired
	private SysManageService sysManageService;
	
	@Override
	protected BaseDao<Office> getBaseDao() {
		return dao;
	}

	@Override
	public int delete(Office query) {
		SysManageServiceImpl.removeCache(SysManageServiceImpl.CACHE_OFFICE_LIST);
		return getBaseDao().delete(query);
	}

	@Override
	public List<Office> findAll() {
		return sysManageService.getOfficeList();
	}
	
	@Override
	public List<Office> findList(Boolean isAll) {
		return (isAll != null && isAll)?dao.selectAll():sysManageService.getOfficeList();
	}

	@Override
	public List<Office> findList(Office office) {
		if (office != null) {
			User user = UserUtils.getUser();
			if (user.isAdmin()) {
				return dao.selectAll();
			} else {
				String parentIds = office.getParentIds();
				office.setParentIds(parentIds + "%");
				// all ancestors node
				if (parentIds != null && parentIds.endsWith(",")) {
					parentIds = parentIds.substring(0, parentIds.length() - 1);
				}
				office.getSqlMap().put("ext", " OR a.id in(" + parentIds + ") ");
				return dao.findByParentIdsLike(office);
			}
		}
		return  new ArrayList<Office>();
	}
	
	public void insertTree(Office entity) {
		// 如果没有设置父节点，则代表为跟节点，有则获取父节点实体
		if (entity.getParent() == null || null==entity.getParentId() 
				|| "0".equals(entity.getParentId())){
			entity.setParent(null);
		}else{
			entity.setParent(dao.selectById(Integer.valueOf(entity.getParentId())));
		}
		if (entity.getParent() == null){
			 
			entity.setParent(new Office(0));
			entity.getParent().setParentIds("");
		}
		
		// 获取修改前的parentIds，用于更新子节点的parentIds
		String oldParentIds = entity.getParentIds(); 
		
		// 设置新的父节点串
		entity.setParentIds(entity.getParent().getParentIds()+entity.getParent().getId()+",");
		
		// 保存或更新实体
		if (entity.getIsNewRecord()){
			entity.preInsert();
			dao.insert(entity);
		}else{
			entity.preUpdate();
			dao.updateById(entity);
		}
		
		// 更新子节点 parentIds
		Office o = new Office();
		o.setParentIds("%,"+entity.getId()+",%");
		List<Office> list = dao.findByParentIdsLike(o);
		for (Office e : list){
			if (e.getParentIds() != null && oldParentIds != null){
				e.setParentIds(e.getParentIds().replace(oldParentIds, entity.getParentIds()));
				dao.updateParentIds(e);
			}
		}
		
		SysManageServiceImpl.removeCache(SysManageServiceImpl.CACHE_OFFICE_LIST);
		
	}

}
